package com.bosssoft.hr.train.springmvc.example.controller;

import com.bosssoft.hr.train.springmvc.example.model.User;
import com.bosssoft.hr.train.springmvc.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * @description 用户登录controller 主要处理用户登录请求 登录页面跳转 用户退出登录
 * @author ChenTong
 * @date 2020/6/5
 */
@Controller
public class LoginController {
    @Autowired
    UserService userService;

    /**
     * 用户登录页面
     * @type Get
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLogin(){
        //返回login.jsp
        return "login";
    }

    /**
     *
     * @param user form表单对象
     * @param model 前端model
     * @param session 请求中的session
     * @type Post
     * @return String page
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(User user, Model model, HttpSession session){
        if (userService.login(user.getName(),user.getPassword())){
            session.setAttribute("USER_SESSION",user);
            //页面重定向
            return "redirect:main";
        }
        model.addAttribute("msg","登录失败");
        //返回登录也买你
        return "login";
    }

    /**
     * 首页
     * @return jsp
     */
    @RequestMapping(value = "/main")
    public String toIndex(){
        return "main";
    }

    /**
     * 用户登出 清理session
     * @param session session
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpSession session){
        //清除session
        session.invalidate();
        //重定向
        return "redirect:login";
    }

}
